package com.osfw.activiti.service.running.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.activiti.entity.history.ActHiVarinst;
import com.osfw.activiti.entity.running.ActRuVar;
import com.osfw.activiti.mapper.running.ActRuVarMapper;
import com.osfw.activiti.service.history.IActHiVarinstService;
import com.osfw.activiti.service.running.IActRuVarService;
import com.osfw.framework.utils.bean.BeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 流程变量表 服务层实现
 */
@Service
public class ActRuVarServiceImpl extends ServiceImpl<ActRuVarMapper, ActRuVar> implements IActRuVarService {

    @Autowired
    private IActHiVarinstService hiVarinstService;

    @Override
    public boolean addGlobalVariables(Long procInstId, Map<String, Object> variables) {
        if(variables != null) {
            List<ActRuVar> ruVarList = variables.entrySet().stream().map(entry -> {
                ActRuVar ruVar = new ActRuVar()
                        .setProcInstId(procInstId)
                        .setProcExecId(null)
                        .setProcTaskId(null)
                        .setVarType(entry.getValue().getClass().getTypeName())
                        .setVarName(entry.getKey())
                        .setVarValue(entry.getValue().toString());
                return ruVar;
            }).collect(Collectors.toList());
            boolean saveBatch = saveBatch(ruVarList);
            if(saveBatch) {
                List<ActHiVarinst> hiVarinstList = BeanMapper.mapAsList(ruVarList, ActHiVarinst.class);
                saveBatch = hiVarinstService.saveBatch(hiVarinstList);
            }
            return saveBatch;
        }
        return false;
    }

    @Override
    public boolean addLocalVariables(Long procInstId, Long procExecId, Long procTaskId, Map<String, Object> variables) {
        if(variables != null) {
            List<ActRuVar> ruVarList = variables.entrySet().stream().map(entry -> {
                ActRuVar ruVar = new ActRuVar()
                        .setProcInstId(procInstId)
                        .setProcExecId(procExecId)
                        .setProcTaskId(procTaskId)
                        .setVarType(entry.getValue().getClass().getTypeName())
                        .setVarName(entry.getKey())
                        .setVarValue(entry.getValue().toString());
                return ruVar;
            }).collect(Collectors.toList());
            boolean saveBatch = saveBatch(ruVarList);
            if(saveBatch) {
                List<ActHiVarinst> hiVarinstList = BeanMapper.mapAsList(ruVarList, ActHiVarinst.class);
                saveBatch = hiVarinstService.saveBatch(hiVarinstList);
            }
            return saveBatch;
        }
        return false;
    }
}
